import {
  Button,
  ColProps,
  Form,
  FormInstance,
  FormItemProps,
  FormProps,
  Space,
} from 'antd';
import { ReactElement, Ref, forwardRef, memo } from 'react';
import { ItemLayout, ItemLayoutPorps } from './ItemLayout';
import { ValueTypeProps, valueTypeRender } from './ValueTypeRender';
import './index.less';

export interface YmQueryFilterProps<Value = any>
  extends Omit<FormProps<Value>, 'children'>,
    Pick<
      ItemLayoutPorps,
      'collapsed' | 'defaultCollapsed' | 'span' | 'onCollapsed'
    > {
  /**
   * @desc formItem的扩展配置
   */
  formItems?: (FormItemProps<Value> & { valueType?: ValueTypeProps } & {
    colProps?: ColProps;
  })[];
  /**
   * @desc 是否显示重置
   */
  hiddenReset?: boolean;
  submitText?: string;
}

function YmQueryFilter<ValueType = any>(
  {
    formItems = [],
    collapsed,
    defaultCollapsed,
    span,
    onCollapsed,
    submitText = '提交',
    hiddenReset,
    ...formProps
  }: YmQueryFilterProps,
  ref: Ref<FormInstance<ValueType>>,
) {
  const items = formItems.map(({ valueType, children, colProps, ...porps }) => {
    const child = children ?? valueTypeRender(valueType ?? { inputProps: {} });
    return {
      ...colProps,
      children: (
        <Form.Item style={{ margin: 0 }} {...porps}>
          {child}
        </Form.Item>
      ),
    };
  });

  return (
    <Form<ValueType>
      ref={ref}
      labelWrap={false}
      labelCol={{ style: { width: 72 } }}
      {...formProps}
    >
      <ItemLayout
        span={span}
        collapsed={collapsed}
        defaultCollapsed={defaultCollapsed}
        onCollapsed={onCollapsed}
        items={items}
        extraRender={(value) => {
          return (
            <Form.Item style={{ margin: 0 }}>
              <Space size={8}>
                <Button htmlType="reset" hidden={hiddenReset}>
                  重置
                </Button>
                <Button type="primary" htmlType="submit">
                  {submitText}
                </Button>
                {value?.collapsedIcon}
              </Space>
            </Form.Item>
          );
        }}
      />
    </Form>
  );
}

export default memo(forwardRef(YmQueryFilter)) as <FormValue = any>(
  props: YmQueryFilterProps<FormValue> & { ref?: Ref<FormInstance<FormValue>> },
) => ReactElement;
